import {synthOption, themeConfig} from "@/storage";
import {getObjectValue, playMessages, quotations, randomNum} from "@/utils";

interface StartMsgByTtsEvent {
  message?: string,
  play?: boolean
}

/**
 * 语音
 */
export const synthUtterance = new SpeechSynthesisUtterance()

/**
 * 获取一个有趣的语音
 */
export const getPlayMessage = async (): Promise<string> => {
  const msg = playMessages[randomNum(playMessages.length - 1)]
  try {
    const quotation = quotations.find(f => f.value === themeConfig.value.quotation)
    const {data} = await fetch(quotation ? quotation.value : themeConfig.value.quotation).then(res => res.json())
    if (Array.isArray(data)) {
      return data.join('，下一条。')
    } else {
      return getObjectValue(data, quotation?.props || ['content'])
    }
  } catch (e) {
    return msg || '没有播放内容'
  }
}
/**
 * 获取一个有趣的语音
 */
export const getPlayDefaultMessage = () => {
  return playMessages[randomNum(playMessages.length - 1)] || '没有播放内容'
}


export const cancelMsgByTts = () => {
  window.speechSynthesis.cancel()
  updateSynthOption()
}

/**
 * 初始化全局TTS事件
 */
export const initSynthEvent = () => {
  synthUtterance.lang = "zh-CN";//使用的语言:中文
  //声音音量:0-1
  synthUtterance.volume = 1;
  //语速:0-10
  synthUtterance.rate = 1.2;
  //音高:0-1
  // synthUtterance.pitch = 0.5;
  // 事件
  synthUtterance.addEventListener('end', () => {
    cancelMsgByTts()
  })
  synthUtterance.addEventListener('error', () => {
    cancelMsgByTts()
  })
  synthUtterance.addEventListener('start', () => {
    updateSynthOption()
  })
  synthUtterance.addEventListener('resume', () => {
    updateSynthOption()
  })
  synthUtterance.addEventListener('pause', () => {
    updateSynthOption()
  })
}

export const startMsgByTts = async (option?: StartMsgByTtsEvent) => {
  // 检查浏览器支持
  if ('speechSynthesis' in window) {
    const synth = window.speechSynthesis
    const config: StartMsgByTtsEvent = option || {}
    if (synth.pending || synth.speaking) {
      if (synth.paused) {
        window.speechSynthesis.resume()
      } else {
        window.speechSynthesis.pause()
      }
    } else {
      if (!config.message) config.message = await getPlayMessage()
      playMsgByTts(config.message, config.play)
    }
  }
}

export const updateSynthOption = () => {
  if ('speechSynthesis' in window) {
    const synth = window.speechSynthesis
    synthOption.value.paused = synth.paused
    synthOption.value.pending = synth.pending
    synthOption.value.speaking = synth.speaking
  }
}

/**
 * 语音播放
 * @param message
 * @param play
 */
export const playMsgByTts = (message: string, play: boolean = false) => {
  if (!themeConfig.value.TTSPlay && !play) return Promise.reject(false)
  if (synthOption.value.pending) cancelMsgByTts()
  return new Promise((resolve, reject) => {
    if ('speechSynthesis' in window) {
      const synth = window.speechSynthesis;
      synthUtterance.text = message;//文字内容
      synth.speak(synthUtterance);
      synthUtterance.onend = resolve
      synthUtterance.onerror = reject
    } else {
      reject(false)
    }
  })
}
